/**
 *   课程模块
 */
const { response } = require("express")
const express = require("express")
const Query = require("./data")
const {verifyToken} = require("./utils")

const router = express.Router()

// 获取同步课程
router.get("/sync",async(req,res) => {
    // 定义sql语句
    let sql = `select * from e_course where type=1 order by id limit 0,8`
    let result = await Query(sql)
    // 优化返回课程的图片路径
    result = result.map(value => {
        return {
            ...value,
            image_src: "http://192.168.11.218:3000/images/course/" + value.image_src
        }
    })
    if(result.length > 0) {
        return res.send({
            errorCode: 200,
            errorMsg: "获取同步课程成功",
            user: [],
            data: result
        })
    }
})

// 获取精品课程
router.get("/boutique",async(req,res) => {
    // 定义sql语句
    let sql = `select * from e_course where type=1 order by id limit 0,6`
    let result = await Query(sql)
    // 优化返回课程的图片路径
    result = result.map(value => {
        return {
            ...value,
            image_src: "http://192.168.11.218:3000/images/course/" + value.image_src
        }
    })
    if(result.length > 0) {
        return res.send({
            errorCode: 200,
            errorMsg: "获取精品课程成功",
            user: [], // TODO 后期完善添加登录用户数据
            data: result
        })
    }
})

//  搜索课程
router.get("/search",async(req,res) => {
    // 获取搜索关键词
    let {keyword="",pageno=1,size=5} = req.query
    if(keyword === "") {
        return res.send({
            errorCode: 300,
            errorMsg: "缺失搜索关键词",
            user: [], // TODO 后期完善添加登录用户数据
            data:[]
        })
    }
    // 定义sql语句
    let start = (parseInt(pageno) -1) * parseInt(size)
    let sql = `select * from e_course where title like ? order by id limit ?, ?`
    let result = await Query(sql,[`%${keyword}%`, start, parseInt(size)])
    // 优化返回课程的图片路径
    result = result.map(value => {
        return {
            ...value,
            image_src: "http://192.168.11.218:3000/images/course/" + value.image_src
        }
    })
    // 获取数据库中的数据条目数量
    let countSql = `select count(1) as cnt from e_course where title like ?`
    let countRes = await Query(countSql,`%${keyword}%`)
    let cnt = countRes[0]['cnt']
    // 计算页码数量
    let pages = Math.ceil(cnt / parseInt(size))
    return res.send({
        errorCode: 200,
        errorMsg: "搜索课程完成",
        user: [],  // TODO 后期完善添加登录用户数据 
        data: [{
            pageno, // 页码
            cnt,    // 条数
            pages,  // 总页码数
            result  // 数据
        }]
    })
})

// 条件查询课程
router.get("/online",async (req,res) => {
    // 解构需要的参数
    let {city="",grade="",subject="",type="",pageno=1,size=5} = req.query
    // 定义sql语句
    let start = (parseInt(pageno) -1) * parseInt(size)
    let paramsArr = []
    let sql = `select * from e_course where 1=1`
    // 查询数据量
    let sntSql = `select count(1) as cnt from e_course where 1=1`
    if(city !== "") {
        sql += `and area_name = ?`
        cntSql += `and area_name = ?`
        paramsArr.push(city)
    }
    if(grade !== "") {
        sql += ` and grade_name = ?`
        cntSql += ` and grade_name = ?`
        paramsArr.push(grade)
    }
    if(subject !== "") {
        sql += ` and subject_name = ?`
        cntSql += ` and subject_name = ?`
        paramsArr.push(subject)
    }
    if(type !== "") {
        sql += ` and category_name = ?`
        cntSql += ` and category_name = ?`
        paramsArr.push(type)
    }
    sql += `order by id limit ?,?`
    paramsArr.push(start,parseInt(size))
    let result = await Query(sql,paramsArr)

    let cntResult = await Query(cntSql,paramsArr)
    console.log(cntResult,cntSql);
    let cnt = cntResult[0]['cnt']
    let pages = Math.ceil(cnt/ parseInt(size))

    // 优化返回课程的图片路径
    result = result.map(value => {
        return {
            ...value,
            image_src: "http://192.168.11.218:3000/images/course/" + value.image_src
        }
    })
    return res.send({
        errorCode: 200,
        errorMsg: "查看课程完成",
        user: [],   // TODO 后期完善添加登录用户数据
        data: [
            {cnt, pages, pageno, result}
        ]
    })
})

// 查看课程详情
router.get("/datail/:cid",async(req,res) => {
    // 获取要查询的课程编号
    let cid = req.params.cid
    // 定义sql语句，查询课程信息
    let sql = `select * from e_course wherw cid = ?`
    let result = await Query(sql,cid)
    // 补充师资信息
    sql = `select * from e_teacher where tid = ?`
    let tRes = await Query(sql,result[0]['tid'])
    tRes = tRes.map(value => {
        return {
            ...value,
            head_photo_url: "http://192.168.11.218:3000/avatar/" + value.head_photo_url,
        }
    })
    // 定义sql语句，查询课程所属视频信息
    sql = `select * from e_video where cid = ? order by vnum`
    let vRes = await Query(sql,cid)
    vRes = vRes.map(value => {
        return {
            ...value,
            video_src: "http://192.168.11.100:3000/video/" + value.video_src,
        }
    })
    // 修正result数据
    resultq = result.map(value => {
        return {
            ...value,
            image_src: "http://192.168.11.218:3000/images/course/" + value.image_src,
            detail_imgs: "http://192.168.11.218:3000/images/course/" + value.detail_imgs,
            video_list: vRes,
            teacher: tRes
        }
    })
    // 返回数据
    return res.send({
        errorCode: 200,
        errorMsg: "查看课程详情成功",
        user: "",
        data: result
    })
})

// 查看视频详情
router.get("/video/:cid/:vid",async(req,res) => {
    let {cid,vid} = req.params
    // 1、获取令牌数据，验证用户是否登录
    let user = verifyToken(req.headers["token"])
    if(!verifyToken(req.headers["token"])) {
        res.send({
            errorCode: 300,
            errorMsg: "查询失败，用户未登录",
            user: "",
            data: []
        })
    }
    // 2、查看用户是否订购课程，订购状态下观看视频
    let vsql = `select * from e_order wherw mid = ? and cid = ?`
    let vers = await Query(vsql,[user.data.mid,cid])
    if(vers.length <= 0) {
        res.end({
            errorCode: 301,
            errorMsg: "查询失败，用户未订购",
            user: "",
            data: []
        })
    }
    // 定义sql语句
    let sql = `select * from e_video where id = ?`
    // 执行sql语句，查询结果数据
    let result = await Query(sql, vid)
    // 处理视频路径
    result = result.map(value => {
        return {
            ...value, 
            video_src: "http://192.168.11.218:3000/video/" + value.video_src
        }
    })
    // 返回视频信息
    res.send({
        errorCode: 200,
        errorMsg: "查询成功",
        user: "",
        data: result
    })
})

module.exports = router